package problem;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 长时间运行的线程 示例
 */
public class LongTimeRunDemo {
    public static void main(String[] args) {
        Runnable[] tasks = new Runnable[] {
                new Runnable() {
                    @Override
                    public void run() {
                        try {
                            TimeUnit.SECONDS.sleep(1);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Runnable() {
                    @Override
                    public void run() {
                        try {
                            TimeUnit.SECONDS.sleep(2);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Runnable() {
                    @Override
                    public void run() {
                        try {
                            TimeUnit.SECONDS.sleep(5);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
        };
        ExecutorService executorService = Executors.newFixedThreadPool(4);
        Random random = new Random();
        for (int i = 0; i < 1000; i++) {
            executorService.execute(tasks[random.nextInt(tasks.length)]);
        }
        executorService.shutdown();
    }
}
